const express = require('express');
const jwt = require('jsonwebtoken');
require('dotenv').config();
const crypto = require('crypto');   //md5加密
const {adminModel} = require('../model/model')
const router = express.Router();

// 生成 Access Token
function generateAccessToken(value) {
    return jwt.sign({ value }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '10s' });
}

// 生成 Refresh Token
function generateRefreshToken(value) {
    return jwt.sign({ value }, process.env.REFRESH_TOKEN_SECRET);
}

router.post('/pc_login', async (req, res) => {
    const { phonenumber, password } = req.body;
    const md5Password = crypto.createHash('md5').update(password).digest('hex');

    let admin = await adminModel.findOne({ phonenumber: phonenumber })
    if (!admin) {
        res.send({
            code: 201,
            msg: '手机号未注册'
        })
        return
    }
    if (admin.password != md5Password) {
        res.send({
            code: 201,
            msg: '密码错误'
        })
        return
    }
    const accessToken = generateAccessToken(admin.phonenumber);
    const refreshToken = generateRefreshToken(admin.phonenumber);
    res.send({
        code: 200,
        accessToken,
        refreshToken,
        msg: '登陆成功',
        adminId: admin._id
    })

});

router.post('/token', (req, res) => {
    const { token } = req.body;
    if (!token) return res.sendStatus(401);
    jwt.verify(token, process.env.REFRESH_TOKEN_SECRET, (err, user) => {
        if (err) return res.sendStatus(403);
        const accessToken = generateAccessToken(user.username);
        res.json({ accessToken });
    });
});




router.post('/admin', (req, res) => {
    const { phonenumber, password } = req.body;
    const hash_password = crypto.createHash('md5').update(password).digest('hex');
    adminModel.create({ phonenumber, password: hash_password })
    res.send({
        code: 200
    })
});


module.exports = router